﻿using System;
using System.Collections.Generic;
using System.Data;

namespace ToolUtil
{
    public class DTable
    {
        public static DataTable ViewTrim(DataTable dt)
        {
            try
            {
                for (int k = 0; k < dt.Rows.Count; k++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                       // Console.WriteLine("字段类型" + dt.Columns[j].DataType.Name);
                        switch (dt.Columns[j].DataType.Name)
                        {
                            case "Decimal": //数字型0置为空
                                if(dt.Rows[k][j] != null)
                                    dt.Rows[k][j] = dt.Rows[k][j].ToString().Trim();
                                break;
                            case "String": //字符型去空
                                if (!string.IsNullOrEmpty(dt.Rows[k][j].ToString()))
                                    dt.Rows[k][j] = dt.Rows[k][j].ToString().Trim();
                                //Console.WriteLine("字段类型" + dt.Rows[k][j]);
                                break;
                        }
                    }
                }
            }
            catch { }
            return dt;
        }
        /// <summary>
        /// datatable去重
        /// </summary>
        /// <param name="dtSource">需要去重的datatable</param>
        /// <param name="columnNames">依据哪些列去重</param>
        /// <returns></returns>
        public static DataTable GetDistinctTable(DataTable dtSource, params string[] columnNames)
        {
            DataTable distinctTable = dtSource.Clone();
            try
            {
                if (dtSource != null && dtSource.Rows.Count > 0)
                {
                    DataView dv = new DataView(dtSource);
                    distinctTable = dv.ToTable(true, columnNames);
                }
            }
            catch { }
            return distinctTable;
        }
        // <summary>
        /// datatable去重
        /// </summary>
        /// <param name="dtSource">需要去重的datatable</param>
        /// <returns></returns>
        public static DataTable GetDistinctTable(DataTable dtSource)
        {
            DataTable distinctTable = null;
            try
            {
                if (dtSource != null && dtSource.Rows.Count > 0)
                {
                    string[] columnNames = GetTableColumnName(dtSource);
                    DataView dv = new DataView(dtSource);
                    distinctTable = dv.ToTable(true, columnNames);
                }
            }
            catch { }
            return distinctTable;
        }
        /// <summary>
        /// 获取所有列
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string[] GetTableColumnName(DataTable dt)
        {
            string cols = string.Empty;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                cols += (dt.Columns[i].ColumnName + ",");
            }
            cols = cols.TrimEnd(',');
            return cols.Split(',');
        }

        public static string _BuildColumnKey="ll";
        public static DataColumn BuildDataColumn(DataColumn pCol, bool pIsTrim)
        {
            DataColumn newCol = new DataColumn();
            newCol.DataType = pCol.DataType;

            if (pIsTrim)
            {
                newCol.ColumnName = pCol.ColumnName + _BuildColumnKey;
                if (pCol.DataType.Name != "Decimal")
                {
                    newCol.Expression = "trim([" + pCol.ColumnName + "])";
                }
            }
            else
            {
                newCol.ColumnName = pCol.ColumnName + _BuildColumnKey;
                newCol.Expression = pCol.ColumnName;
            }

            return newCol;
        }

        static DataColumn BuildRestoreDataColumn(DataColumn pCol)
        {
            DataColumn newCol = new DataColumn();
            newCol.DataType = pCol.DataType;
            if (pCol.ColumnName.Contains(_BuildColumnKey))
            {
                newCol.ColumnName = pCol.ColumnName.Replace(_BuildColumnKey, "");
            }
            newCol.Expression = pCol.ColumnName;

            return newCol;
        }

        static Dictionary<string, DataColumn> dicColl = new Dictionary<string, DataColumn>();
        static Dictionary<string, DataColumn> dicAllColl = new Dictionary<string, DataColumn>();
        /// <summary>
        /// 上面的属性开放 Enabled DataGrid Format 有处理这个情况，开放属性就就可以了
        /// </summary>
        /// <param name="pDt"></param>
        public static DataTable TrimValueForOutPut(DataTable pDt)
        {

            DataTable newDtFinal = null;

            if (pDt == null)
                return newDtFinal;

            try
            {
                //Utils.ShowWaitDialog();
                int colIndex = 0;
                string[] columnList = new string[] { };
                string columnListStr = "";

                if (dicColl.Count == 0)
                {
                    foreach (DataColumn col in pDt.Columns)
                    {
                        string key = string.Format("{0}_{1}", colIndex, col.ColumnName);
                        if (col.DataType.Name == "Decimal"
                            || col.DataType.Name == "String")
                        {
                            if (!dicColl.ContainsKey(key))
                            {
                                dicColl.Add(key, col);

                            }
                        }
                    }
                    DataColumn[] Coll = new DataColumn[] { };
                    foreach (DataColumn col in pDt.Columns)
                    {
                        string key = string.Format("{0}_{1}", colIndex, col.ColumnName);
                        dicAllColl.Add(key, col);
                        colIndex++;
                    }
                }

                DataTable newDt = pDt.Copy();

                foreach (var col in dicAllColl)
                {
                    if (dicColl.ContainsKey(col.Key))
                    {
                        newDt.Columns.Add(BuildDataColumn(col.Value, true));
                        columnListStr += col.Value.ColumnName + _BuildColumnKey + ";";
                    }
                    else
                    {
                        newDt.Columns.Add(BuildDataColumn(col.Value, false));
                        columnListStr += col.Value.ColumnName + _BuildColumnKey + ";";
                    }
                }

                columnList = columnListStr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                DataTable newDt2 = newDt.DefaultView.ToTable(false, columnList);

                columnListStr = "";
                DataTable newDTRes = newDt2.Copy();
                foreach (DataColumn col in newDt2.Columns)
                {
                    newDTRes.Columns.Add(BuildRestoreDataColumn(col));
                    columnListStr += col.ColumnName.Replace(_BuildColumnKey, "") + ";";
                }


                columnList = columnListStr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                newDtFinal = newDTRes.DefaultView.ToTable(false, columnList);

                if (newDtFinal != null && newDtFinal.Rows.Count == pDt.Rows.Count)
                {
                    pDt = newDtFinal;
                }
                return newDtFinal;
            }
            catch
            {
                return newDtFinal;
            }
        }
    }
}
